import React from "react";
import "./index.css";
import Selfmessage from "../Selfmessage/Selfmessage";
import Othermessage from "../Othermessage/Othermessage";
export default class Right extends React.Component {
  constructor() {
    super();
    this.state = {
      websocket: new WebSocket("ws://172.16.34.171:3000"),
      msgList: null,
      userlist: null,
    };
  }
  componentDidMount() {
    this.state.websocket.onopen = this.send;
    this.state.websocket.onclose = () => {
      const json = JSON.stringify({
        text: "close",
        username: this.props.username,
      });
      this.state.websocket.send(json);
    };
  }

  send = () => {
    const text = document.getElementById("text").value;
    const chatBox = document.getElementById("right-mid");
    const json = JSON.stringify({
      text,
      username: this.props.username,
    });
    this.state.websocket.send(json);
    this.state.websocket.onmessage = this.onmessage;
    setTimeout(() => {
      chatBox.scrollTop = chatBox.scrollHeight;
    }, 30);
    document.getElementById("text").value = "";
  };
  onmessage = (msg) => {
    console.log(JSON.parse(msg.data));
    const msgObj = JSON.parse(msg.data);
    this.setState({
      msgList: msgObj.msglist,
      userlist: msgObj.userlist,
    });
  };
  keydown = (e) => {
    if (e.keyCode == 13) {
      this.send();
    }
  };
  render() {
    const { username } = this.props;
    const { msgList, userlist } = this.state;
    return (
      <>
        <div className="right-container">
          <div className="right-header">
            聊天室({userlist ? userlist.length : 0})
          </div>
          <div className="right-mid" id="right-mid">
            {msgList
              ? msgList.map((msg, index) => {
                  if (msg.addUser) {
                    return (
                      <div key={index} className="new-user">
                        "{msg.name}"加入了群聊
                      </div>
                    );
                  }
                  if (msg.username == username) {
                    return (
                      <Selfmessage
                        key={index}
                        username={username}
                        message={msg.text}
                      />
                    );
                  }
                  return (
                    <Othermessage
                      key={index}
                      username={msg.username}
                      message={msg.text}
                    />
                  );
                })
              : ""}
          </div>
          <div className="right-footer">
            <textarea
              id="text"
              className="input"
              onKeyDown={this.keydown}
            ></textarea>
            <div className="commit" onClick={this.send}>
              发送(Enter)
            </div>
          </div>
        </div>
      </>
    );
  }
}
